package net.wanho.config;

import net.wanho.shiro.filter.JwtFilter;
import net.wanho.shiro.matcher.JwtMatcher;
import net.wanho.shiro.realm.ShiroRealm;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.authc.credential.SimpleCredentialsMatcher;
import org.apache.shiro.realm.Realm;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.servlet.Filter;
import java.util.LinkedHashMap;
import java.util.Map;

@Configuration
public class ShiroConfig {

    /**
     * ShiroFilter
     */
    @Bean
    public ShiroFilterFactoryBean filterFactoryBean(DefaultWebSecurityManager securityManager){
        ShiroFilterFactoryBean factoryBean = new ShiroFilterFactoryBean();

        // 设置安全管理器
        factoryBean.setSecurityManager(securityManager);

        // 自定义过滤器
        Map<String, Filter> filterMap = new LinkedHashMap<>();
        filterMap.put("jwtFilter",new JwtFilter());
        factoryBean.setFilters(filterMap);

        // 设置url过滤规则
        Map<String, String> chainMap = new LinkedHashMap<>();
        chainMap.put("/captchaImage","anon");
        chainMap.put("/login","anon");
        // 放行swagger
        chainMap.put("/doc.html","anon");
        chainMap.put("/webjars/**/**","anon");
        chainMap.put("/swagger/**","anon");
        chainMap.put("/v2/**","anon");
        chainMap.put("/static/**","anon");
        chainMap.put("/swagger-resources/**","anon");

        chainMap.put("/**","jwtFilter");
        factoryBean.setFilterChainDefinitionMap(chainMap);

        return factoryBean;
    }

    /**
     * 安全管理器
     */
    @Bean
    public DefaultWebSecurityManager securityManager(Realm realm){
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();

        // 设置Realm
        securityManager.setRealm(realm);

        return securityManager;
    }

    /**
     * Realm源
     */
    @Bean
    public ShiroRealm shiroRealm(){
        ShiroRealm realm = new ShiroRealm();
        // 使用JwtMatcher凭证匹配器，对token进行判断
        realm.setCredentialsMatcher(new JwtMatcher());
        return realm;
    }

}